﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using GaiNo.Core.Helpers;
using System.IO;
using System.Web.Caching;
using System.Text.RegularExpressions;
namespace GaiNo.Core.Services
{
    public class LanguageResource : ILanguageResource
    {
        LanguageType _language = LanguageType.en;
        public LanguageResource()
        {
            _language = GetLanguageType();
        }
        protected virtual LanguageType GetLanguageType()
        {
            return LanguageType.en;
        }
        private XDocument GetDoc(LanguageType type)
        {
            string key = "_LANGUAGES_" + type.ToString().ToUpper();
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resource\\Languages\\");
            if (!FileHelper.IsDirectoryExist(path))
                FileHelper.CreateDirectory(path);

            path = path + type.ToString() + ".lang";

            CacheHelper cm = CacheHelper.CreateInstance();
            XDocument doc = null;
            object cache = cm.Get(key);
            if (cache != null)
                doc = cache as XDocument;
            else
            {
                if (!FileHelper.IsFileExist(path))
                    XDocument.Parse("<Resources />").Save(path);

                doc = XDocument.Load(path);

                CacheDependency cd = new CacheDependency(path);
                cm.Add(key, doc, cd, new TimeSpan(24, 0, 0, 0));
            }
            return doc;
        }
        #region ILanguageRecource 成员

        public string GetResource(string key)
        {
            return GetResource(key, _language);
        }
        public string GetResource(string key, LanguageType type)
        {
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resource\\Languages\\" + type.ToString() + ".lang");
            var doc = GetDoc(type);
            var xmlKey = Regex.Replace(key, @"\.|,|!|\?|\-|\(|\)", "");//key.ToUpper();
            xmlKey = xmlKey.Replace(" ", "_");
            xmlKey = xmlKey.ToUpper();
            var ele = doc.Root.Elements("Resource").FirstOrDefault(e => e.Attribute("Name").Value == xmlKey);
            if (ele != null)
                return ele.Value;
            else
            {
                var newElement = new XElement("Resource") { Value = key };
                newElement.SetAttributeValue("Name", xmlKey);
                doc.Root.Add(newElement);
                doc.Save(path);
            }
            return key;
        }

        #endregion
    }
}
